import React from 'react';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col} from 'antd';
import {FORM_OPTIONS, FORM_ROW_OPTIONS} from '../constants';
import {PERMISSION, salePlanAssembleMethod} from './constants';
import {baseDataStatus} from '../Enum';
import WrappedSelect from '../common/WrappedSelect';
import DateRangePicker from 'Shared/components/DateRangePicker';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import SearchSelectPanel from '../common/DutyUnitSelect/SelectEdit';
import ImportPanel from './ImportPanel';
import TagSelect from 'Shared/components/TagSelect';
import {hasPermissions} from './utils';
import {injectIntl, language} from './intl';
import Export from '../common/Export';
import {getMarketDepartment, getMarketDepartmentSimple} from './api';
import WrappedInputNumber from '../common/WrappedInputNumber';
const FormItem = Form.Item;
const EMPTY_ARRAY = [];
class QueryPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        data: {},
        showSaleModelPanel: false,
        showImportPanel: false
    }
    handleFilterChange = (value, name) => {
        this.props.onConditionsChange(name, value);
    }
    onChangeImport = () => {
        this.setState({
            showImportPanel: true
        });
    }
    onCloseImportPanel = () => {
        this.setState({
            showImportPanel: false
        });
    }
    onImportChange = data => {
        if(data)
            this.setState({
                showImportPanel: false
            });
    }
    onSelectDealer = data => {
        this.handleFilterChange(data.id, 'dealerId');
        this.props.onSelect({
            id: data.id,
            code: data.code,
            name: data.name,
        });
    }
    render() {
        const operations = [];
        const {conditions, queryDealer} = this.props;
        const dealerInfo = conditions.dealerId ? {
            id: queryDealer.id,
            code: queryDealer.code,
            name: queryDealer.name
        } : null;
        const markeInfo = conditions.marketDepartmentId ? {
            id: conditions.marketDepartmentId,
            name: conditions.marketDepartmentName
        } : null;
        if(hasPermissions(this.props.permissions, PERMISSION.import))
            operations.push(<Button key="import" onClick={this.onChangeImport}>{this.props.intl.formatMessage({
                id: 'queryPanel.operation.import',
                defaultMessage: '导入'
            })}</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.export))
            operations.push(
                <Export key={PERMISSION.export} exportRequest={this.props.onClickExport} />
            );
        return (
            <Form className="form-standard">
                <Row>
                    {this.props.brands.length > 1 ? <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.brandId',
                                defaultMessage: '品牌'
                            })}
                            {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                name="brandId"
                                allowClear
                                value={this.props.conditions.brandId}
                                options={this.props.brands}
                                onChange={this.handleFilterChange} />
                        </FormItem>
                    </Col> : null}
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.businessType',
                                defaultMessage: '装配方式'
                            })}
                            {...FORM_OPTIONS.item}>
                            <WrappedSelect
                                allowClear
                                name="businessType"
                                value={this.props.conditions.businessType}
                                options={salePlanAssembleMethod.toList(language)}
                                onChange={this.handleFilterChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.marketDepartmentId',
                                defaultMessage: '大区'
                            })}
                            {...FORM_OPTIONS.item}>
                            <SearchSelectPanel
                                value={markeInfo}
                                getDutyUnits={getMarketDepartment}
                                getDutyUnitSimple={getMarketDepartmentSimple}
                                titleName={this.props.intl.formatMessage({
                                    id: 'queryPanel.form.marketDepartmentId',
                                    defaultMessage: '大区'
                                })}
                                isLabelMap={false}
                                onSelect={this.props.onSelectMarke} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.dealerId',
                                defaultMessage: '总代'
                            })}
                            {...FORM_OPTIONS.item}>
                            <DealerSelectPanel
                                value={dealerInfo}
                                onSelect={this.onSelectDealer} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem
                            label={this.props.intl.formatMessage({
                                id: 'queryPanel.form.planYear',
                                defaultMessage: '计划年份'
                            })}
                            {...FORM_OPTIONS.item}>
                            <WrappedInputNumber
                                min={0}
                                precision={0}
                                name="planYear"
                                value={this.props.conditions.planYear}
                                onBlur={this.handleFilterChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={this.props.intl.formatMessage({
                            id: 'queryPanel.form.createTime',
                            defaultMessage: '创建时间'
                        })} {...FORM_OPTIONS.item}>
                            <DateRangePicker
                                name="createTime"
                                value={this.props.conditions.createTime}
                                onChange={this.handleFilterChange} />
                        </FormItem>
                    </Col>
                    <Col {...FORM_OPTIONS.col}>
                        <FormItem label={this.props.intl.formatMessage({
                            id: 'queryPanel.form.status',
                            defaultMessage: '状态'
                        })} {...FORM_OPTIONS.item}>
                            <TagSelect
                                name="status"
                                value={conditions.status}
                                options={baseDataStatus.toList(language)}
                                onChange={this.handleFilterChange} />
                        </FormItem>
                    </Col>
                </Row>
                <Row>
                    <Col span={6}>
                        <Button key="query" type="primary" onClick={this.props.querySearch} loading={this.props.loading}>
                            {this.props.intl.formatMessage({
                                id: 'queryPanel.btn.query',
                                defaultMessage: '查询'
                            })}
                        </Button>
                        <Button key="clear" onClick={this.props.onResetClick}>
                            {this.props.intl.formatMessage({
                                id: 'queryPanel.btn.onResetClick',
                                defaultMessage: '重置'
                            })}
                        </Button>
                    </Col>
                    <Col span={18} className="col-align-right">
                        {operations}
                    </Col>
                </Row>
                {
                    this.state.showImportPanel &&
                    <ImportPanel
                        selectKey={'1'}
                        onCancel={this.onCloseImportPanel}
                        onImportChange={this.onImportChange} />
                }
            </Form>
        );
    }
}

QueryPanel.propTypes = {
    brands: PropTypes.array.isRequired,
    conditions: PropTypes.object.isRequired,
    loading: PropTypes.bool.isRequired,
    permissions: PropTypes.array.isRequired,
    querySearch: PropTypes.func.isRequired,
    onClickExport: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onResetClick: PropTypes.func.isRequired,
    onSelectMarke: PropTypes.func.isRequired,
    intl: PropTypes.object,
};

import {connect} from 'react-redux';
import {
    saveQueryCondition,
    resetQueryPanel,
    querySearch,
    exportData,
    saveQueryDealer,
    selectMarkeQuery
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';

const getBrandsData = createSelector(
    state => state.getIn(['page', 'domainData', 'brands', 'data']),
    initData => {
        const data = initData.toJS() || EMPTY_ARRAY;
        return data.map(item => ({
            text: item.name,
            value: item.id
        }));
    }
);

const getConditions = selectorFactory(['page', 'appState', 'queryCondition']);
const getQueryDealer = selectorFactory(['page', 'appState', 'queryDealer']);
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);
const mapStateToProps = state => ({
    loading: state.getIn((['page', 'domainData', 'list', 'isFetching'])),
    brands: getBrandsData(state),
    queryDealer: getQueryDealer(state),
    conditions: getConditions(state),
    permissions: getPermissions(state),
});

const mapDispatchToProps = dispatch => ({
    onConditionsChange: (name, value) => dispatch(saveQueryCondition(name, value)),
    onSelect: data => dispatch(saveQueryDealer(data)),
    onSelectMarke: data => dispatch(selectMarkeQuery(data)),
    querySearch: () => dispatch(querySearch()),
    onResetClick: () => dispatch(resetQueryPanel()),
    onClickExport: () => dispatch(exportData()),
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(QueryPanel));
